package cn.template.serve_project.exception.handler;

import cn.template.serve_project.constant.HeaderConstant;
import cn.template.serve_project.enums.R;
import cn.template.serve_project.exception.BusinessException;
import cn.template.serve_project.result.Result;
import cn.template.serve_project.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 全局异常处理
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandling {

    @Resource
    private MessageSource messageSource;

    /**
     * 没有捕捉到的异常处理
     */
    @ExceptionHandler(Exception.class)
    public Result<?> doException(Exception ex) {
        log.error("未知异常：{}",ex);
        ex.printStackTrace();
        return Result.error(R.ERROR_EXCEPTION, handlerMsg(R.ERROR_EXCEPTION.msg));
    }

    //业务异常处理
    @ExceptionHandler(value = {BusinessException.class})
    public Result<?> doBusinessException(BusinessException ex) {
        log.error("异常==>{}" + ex.getException());
        log.error("code---------------》{}" + ex.getCode());
        log.error("args---------------》{}" + ex.getArgs());
        log.error("msg---------------》{}" + ex.getMessage());
        return Result.error(ex.getCode(), handlerMsg(ex.getMessage()));
    }

    //不加@RequestBody注解的校验失败抛BindException异常
    @ExceptionHandler(value = {BindException.class})
    public Result<?> doBusinessException(BindException ex) {
        List<String> msg = ex.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return Result.error(R.ERROR_QUERY, handlerMsg(msg));
    }


    /**
     * 添加@RequestBody注解的校验失败抛MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(BindException ex) {
        List<String> msg = ex.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return Result.error(R.ERROR_QUERY, handlerMsg(msg));
    }


    /**
     * 基本数据类型添加@NotBlank等注解校验失败抛ConstraintViolationException异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException ex) {
        List<String> msg = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessageTemplate).collect(Collectors.toList());
        return Result.error(R.ERROR_QUERY, handlerMsg(msg));
    }

    /**
     * 当请求需要接受数据，但请求体为空时
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        return Result.error(R.ERROR_QUERY, handlerMsg(R.ERROR_QUERY.msg));
    }


    public static String getLocal() {
        String lang = HttpUtil.getHttpInfo().getHeader(HeaderConstant.LANGUAGE);
        if (Objects.nonNull(lang)) {
            return lang;
        }
        return "zh";
    }

    public String handlerMsg(String msg) {
        try {
            return messageSource.getMessage(msg, null, Locale.forLanguageTag(getLocal()));
        } catch (Exception e) {
            e.printStackTrace();
            return msg;
        }
    }

    public String handlerMsg(List<String> msg) {
        return String.join(",", msg);
    }
}
